from flask import Blueprint, render_template, request, jsonify, redirect, url_for, make_response
from .db_config import get_db_connection
import datetime
import uuid

main = Blueprint('main', __name__)

# @main.before_request
# def before_request():
#     # 确保在代理环境下正确处理scheme
#     if request.headers.get('X-Forwarded-Proto') == 'http':
#         url = request.url.replace('http://', 'https://', 1)
#         code = 301
#         return redirect(url, code=code)

@main.route('/')
def index():
    user_id = request.cookies.get('user_id')

    conn = get_db_connection()
    cur = conn.cursor()

    if not user_id:
        # 第一次访问，生成新的 UUID
        new_user_id = str(uuid.uuid4())
        cur.execute("INSERT INTO visitors (user_id, created_at) VALUES (%s, %s)", (new_user_id, datetime.datetime.now()))
        conn.commit()

        response = make_response(redirect(url_for('main.index')))
        response.set_cookie('user_id', new_user_id, max_age=60*60*24*365)  # 保存一年
        cur.close()
        conn.close()
        return response
    else:
        # 已存在用户
        cur.execute("SELECT user_id FROM visitors WHERE user_id = %s", (user_id,))
        result = cur.fetchone()

        if not result:
            # 理论上不会出现，如果cookie乱了就重新生成
            new_user_id = str(uuid.uuid4())
            cur.execute("INSERT INTO visitors (user_id, created_at) VALUES (%s, %s)", (new_user_id, datetime.datetime.now()))
            conn.commit()
            response = make_response(redirect(url_for('main.index')))
            response.set_cookie('user_id', new_user_id, max_age=60*60*24*365)
            cur.close()
            conn.close()
            return response

        visitor_id = result[0]
        cur.execute("SELECT content, created_at FROM wishes WHERE visitor_id = %s ORDER BY created_at DESC", (visitor_id,))
        wishes = cur.fetchall()
        
        # 获取birth_name
        cur.execute("SELECT birth_name FROM visitors WHERE user_id = %s", (user_id,))
        birth_name_result = cur.fetchone()
        birth_name = birth_name_result[0] if birth_name_result and birth_name_result[0] else ''
        
        cur.close()
        conn.close()

        return render_template('index.html', wishes=wishes, birth_name=birth_name)

@main.route('/wish')
def wish():
    return render_template('wish.html')

@main.route('/selfwish')
def selfwish():
    return render_template('selfwish.html')

@main.route('/submit_wish', methods=['POST'])
def submit_wish():
    data = request.get_json()
    content = data.get('content')

    user_id = request.cookies.get('user_id')

    if not user_id or not content:
        return jsonify({"status": "error", "message": "Missing user ID or content"}), 400

    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute("SELECT user_id FROM visitors WHERE user_id = %s", (user_id,))
    result = cur.fetchone()

    if not result:
        return jsonify({"status": "error", "message": "Invalid user"}), 400

    visitor_id = result[0]
    cur.execute("INSERT INTO wishes (visitor_id, content, created_at) VALUES (%s, %s, %s)", (visitor_id, content, datetime.datetime.now()))
    conn.commit()
    cur.close()
    conn.close()

    return jsonify({"status": "success"})


@main.route('/get_wishes')
def get_wishes():
    user_id = request.cookies.get('user_id')
    if not user_id:
        return jsonify([])
    status = request.args.get('status', 'active')  # 获取status参数，默认为active
    conn = get_db_connection()
    cur = conn.cursor()
    
    if status == 'active':
        q_sql = """
            SELECT w.id, w.content, w.created_at, w.status 
            FROM wishes w
            JOIN visitors v ON w.visitor_id = v.user_id
            WHERE v.user_id = %s AND (w.status IS NULL OR w.status = 'active')
            ORDER BY w.created_at DESC
        """
    else:
        q_sql = """
            SELECT w.id, w.content, w.created_at, w.status 
            FROM wishes w
            JOIN visitors v ON w.visitor_id = v.user_id
            WHERE v.user_id = %s
            ORDER BY w.created_at DESC
        """
    
    try:
        cur.execute(q_sql, (user_id,))
        wishes = cur.fetchall()
        
        result = []
        for wish in wishes:
            result.append({
                'id': wish[0],
                'content': wish[1],
                'created_at': wish[2].isoformat(),
                'status': wish[3]  # 直接返回status字段，无需进行额外的转换
            })
            
        return jsonify(result)
    except Exception as e:
        print('获取愿望失败:', e)
        return jsonify([])
    finally:
        cur.close()
        conn.close()

@main.route('/delete_wish', methods=['POST'])
def delete_wish():
    data = request.get_json()
    wish_id = data.get('id')
    user_id = request.cookies.get('user_id')
    
    if not wish_id or not user_id:
        return jsonify({"status": "error", "message": "参数缺失"}), 400
    
    conn = get_db_connection()
    cur = conn.cursor()
    
    try:
        # 先验证愿望属于当前用户
        cur.execute("""
            SELECT w.id 
            FROM wishes w
            JOIN visitors v ON w.visitor_id = v.user_id
            WHERE w.id = %s AND v.user_id = %s
        """, (wish_id, user_id))
        
        if not cur.fetchone():
            return jsonify({"status": "error", "message": "无权删除该愿望"}), 403
        
        # 删除愿望
        cur.execute("UPDATE wishes SET status = 'delete' WHERE id = %s", (wish_id,))
        conn.commit()
        
        return jsonify({"status": "success"})
    except Exception as e:
        print('标记删除愿望失败:', e)
        return jsonify({"status": "error", "message": "标记删除失败"}), 500
    finally:
        cur.close()
        conn.close()

# 可以删除以下路由，因为功能已合并到index路由中
@main.route('/get_birth_name')
def get_birth_name():
    user_id = request.cookies.get('user_id')
    if not user_id:
        return jsonify({'name': ''})
    
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute("SELECT birth_name FROM visitors WHERE user_id = %s", (user_id,))
    result = cur.fetchone()
    cur.close()
    conn.close()
    
    return jsonify({'name': result[0] if result and result[0] else ''})

@main.route('/update_birth_name', methods=['POST'])
def update_birth_name():
    user_id = request.cookies.get('user_id')
    if not user_id:
        return jsonify({'success': False})
    
    data = request.get_json()
    new_name = data.get('name', '').strip()
    if not new_name:
        return jsonify({'success': False})
    
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute("UPDATE visitors SET birth_name = %s WHERE user_id = %s", (new_name, user_id))
    conn.commit()
    cur.close()
    conn.close()
    
    return jsonify({'success': True})

@main.route('/get_birthday')
def get_birthday():
    user_id = request.cookies.get('user_id')
    if not user_id:
        return jsonify({'birthday': '1988-05-12'})
    
    conn = get_db_connection()
    cur = conn.cursor()
    cur.execute("SELECT birthday FROM visitors WHERE user_id = %s", (user_id,))
    result = cur.fetchone()
    cur.close()
    conn.close()
    
    return jsonify({'birthday': str(result[0]) if result and result[0] else '1988-05-12'})

@main.route('/update_birthday', methods=['POST'])
def update_birthday():
    user_id = request.cookies.get('user_id')
    if not user_id:
        return jsonify({'success': False})
    
    data = request.get_json()
    new_birthday = data.get('birthday')
    if not new_birthday:
        return jsonify({'success': False})
    
    conn = get_db_connection()
    cur = conn.cursor()
    try:
        cur.execute("UPDATE visitors SET birthday = %s WHERE user_id = %s", 
                   (new_birthday, user_id))
        conn.commit()
        return jsonify({'success': True})
    except Exception as e:
        print('更新生日失败:', e)
        return jsonify({'success': False})
    finally:
        cur.close()
        conn.close()
